import React, { useEffect, useState } from 'react'
import './article.scss'
import ReactQuill from 'react-quill'; 
import 'react-quill/dist/quill.snow.css';
import MySelectOptions from '@/component/selectOption/MySelectOptions'
import {Upload} from '@/component'
import {useDispatch, useSelector} from 'react-redux'
import {handleAddArticle,handleArticleInfo } from '@/store2/actions'
import {
  Form,
  Input, 
  Button, 
} from 'antd'
export default props => {
  // console.log(props);
  const [form] = Form.useForm();
  const [content, setContent] = useState('')
  const [id, setId] = useState(null)
  const info = useSelector(store => store.article.info)
  const dispatch = useDispatch()
  const modules = {
    toolbar: [
      [{ 'header': [1, 2, false] }],
      ['bold', 'italic', 'underline','strike', 'blockquote'],
      [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
      ['link', 'image'],
      ['clean']
    ],
  }
  useEffect(() => {
    const id = props.location.search.split('=')[1]
    setId(id)
    id && dispatch(handleArticleInfo(id))
    return () => undefined
  },[])
  
  useEffect(() => {
    if(id) {
      info.content && setContent(info.content)
      form.setFieldsValue(info)
    }
    return undefined
    
  }, [info])

  const submit = data => {
    data.content = content
    id && (data.id = id)
    console.log(data);
    dispatch(handleAddArticle({data, back: () => {
      props.history.goBack()
    }}))
  }
  return (
    <div className="my-article-info">
      <Form
        style={{maxWidth: '90%', margin: 'auto'}}
        onFinish={submit}
        form={form}
      >
        <div style={{display:'flex'}}>
          <div>
            <Form.Item 
              label="文章标题" 
              name="title"
              rules={[{required: true,message: '必填参数！'}]}
            >
              <Input placeholder="请输入标题" allowClear style={{minWidth: 300}} />
            </Form.Item>
            <Form.Item
              label="文章类别" 
              rules={[{required: true,message: '必填参数！'}]}
              name="cate"
            >
              <MySelectOptions />
            </Form.Item>
          </div>
          <Form.Item 
            label="封面 " 
            name="img" 
            style={{marginLeft: '15%'}}
            rules={[{required: true,message: '必填参数！'}]}
            >
            <Upload />
          </Form.Item>
        </div>
        <Form.Item 
          style={{marginTop: 20}} 
          rules={[{required: true,message: '必填参数！'}]}
        >
          <ReactQuill 
            placeholder="请输入文章内容！" 
            value={content || ''}
            onChange={value => setContent(value)}
            modules={modules}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">提交</Button>
        </Form.Item>
      </Form>
    </div>
  )
}